# -*- coding: UTF-8 -*-

import random

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

from kivy.properties import ObjectProperty
from model.gamestate import *
from ui.hat_widget import HatWidget


def rgb(s):
    r = s[:2]
    g = s[2:4]
    b = s[4:]
    return [int(r, 16) / 255.00, int(g, 16) / 255.0, int(b, 16) / 255.0, 1]


teams_color = [rgb('FF4F00'), rgb('E40045'), rgb('D235D2'),
               rgb('620CAC'), rgb('65E080'), rgb('A5EF00'),
               rgb('FFDD40')]


class PlayerLine(BoxLayout):
    def __init__(self, player, team_id, index, func_swap, root, **kwargs):
        """ creates part with player and team info

        Args:
        player: (Player)
        team_id: (number)
        index: (number) index from top
        func_swap: (callback with args ((number), (number)))
            function to call to swap two neibour players order
        """

        self.color = teams_color[team_id % len(teams_color)]
        self.player = player
        self.func_swap = func_swap
        self.root = root
        super(PlayerLine, self).__init__(**kwargs)
        self.index = index

    def swap_butt_pressed(self, index, button):
        if self.root.sw_butt_idx is None:
            self.root.sw_butt_idx = index
            self.root.butt_pressed = button
        elif self.root.sw_butt_idx == index:
            self.root.sw_butt_idx = None
            self.root.butt_pressed = None
        else:
            self.func_swap(self.root.sw_butt_idx, index)
            self.root.butt_pressed.state = 'normal'
            self.root.butt_pressed.state = 'normal'
            self.root.sw_butt_idx = None
            self.root.butt_pressed = None

    def up_down_pressed(self, index, delta):
        players_count = len(self.root.gamestate.players.players)
        index2 = index + delta
        if players_count - 1 < index2:
            index2 = players_count - 1
        if 0 > index2:
            index2 = 0
        self.func_swap(index, index2)


class PlayerLabel(Label):
    def set_player(self, player):
        """ set player info

        Args:
        player: (Player)
        """

        self.text = player.name
        self.player = player
        self.texture_update()


class PlayersOrderWidget(HatWidget):
    def __init__(self, gamestate, presenter, **kwargs):
        """ Construct PlayersOrder screen

        need:
        valid gamestate.players.players

        do:
        shuffles gamestate.players.players
        creates gamestate.players.strategy
        changes phase to FROM_TO

        Args:
        gamestate: (GameState)
        presenter: (Presenter)
        """

        super(PlayersOrderWidget, self).__init__(**kwargs)
        self.player_list.\
            bind(minimum_height=self.player_list.setter('height'))
        self.gamestate = gamestate
        self.presenter = presenter
        if (len(self.gamestate.players.players) % 2 == 0):
            self.num_teams = len(self.gamestate.players.players) / 2
            self.gamestate.players.set_next_pair_strategy(
                TraditionalStrategy(self.gamestate.players.players))
        else:
            self.num_teams = 1
            self.gamestate.players.set_next_pair_strategy(
                OddStrategy(self.gamestate.players.players))

        self.butt_pressed = None
        self.sw_butt_idx = None

        self.render_all()

    def swap_players(self, index1, index2):
        """ swap players at (index1) to (index2) positions
        Args:
        index1: (number) 1-st player to move
        index2: (number) 2-nd player to move
        """
        players = self.gamestate.players.players
        #if not index2 in range(len(players)):
        # return
        players[index1], players[index2] = \
            players[index2], players[index1]
        self.render_all()

    def render_all(self):
        """ renders all players
        """
        self.player_list.height =\
            len(self.gamestate.players.players) * self.height * 0.1
        self.player_list.clear_widgets()
        cur_team = 0
        cur_index = 0
        for player in self.gamestate.players.players:
            self.player_list.add_widget(PlayerLine(player, cur_team, cur_index,
                                                   self.swap_players, self))
            cur_team = (cur_team + 1) % self.num_teams
            cur_index += 1

    def shuffle(self):
        """ randomly shuffle players
        call on release 'Случайный порядок' button
        """

        random.shuffle(self.gamestate.players.players)
        self.render_all()

    def finish(self):
        """ changes phase to FROM_TO
        call on release 'Начать' button
        """

        self.presenter.change_phase(Phase.FROM_TO)

    def go_back(self):
        self.presenter.change_phase(Phase.START_GAME)


class PlayersOrderApp(App):
    def build(self):
        return


if __name__ == '__main__':
    import doctest

    doctest.testmod()
